package com.alibaba.cloud.boot.order.config;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class WebLogMdcHandlerInterceptor  extends HandlerInterceptorAdapter {

    public String getRandomTenantId(){
        int randInt = ThreadLocalRandom.current().nextInt();
        if (randInt%2==1){
            return "00001";
        }else {
            return "00002";
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("tenantId", getRandomTenantId());
        System.out.println("请求租户id"+MDC.get("tenantId"));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,
                                               HttpServletResponse response, Object handler) throws Exception {
        preHandle(request, response, handler);
    }

}
